package com.wyy.servlet.web;

import com.wyy.bean.Users;
import com.wyy.service.UsersService;
import com.wyy.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName LoginServlet
 * @Description //TODO
 * @Author wky
 * @Date 2021/9/12 14:59
 * @Version 1.0
 **/

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调取service
        UsersService usersService = new UsersServiceImpl();
        Users user = usersService.login(username, password);
        
        //3.跳转页面
        if (user == null){
            //以弹窗方式提示用户登入失败
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';" +
                    "alert('用户名或密码不正确！');</script>");
        }else{
            //保存用户信息
            req.getSession().setAttribute("user1",user);
            //跳转到主页面
            resp.sendRedirect("index.jsp");
    
        }
        
        
    }
}
